<template>
  <div class="rental-dashboard">
    <h1 class="dashboard-title">租房市场可视化分析</h1>
    <div class="dashboard-subtitle">郑州地区</div>

    <div class="chart-container">
      <div class="chart-row">
        <div class="chart-item" ref="priceChart" style="width: 50%; height: 400px;"></div>
        <div class="chart-item" ref="areaChart" style="width: 50%; height: 400px;"></div>
      </div>

      <div class="chart-row">
        <div class="chart-item" ref="typeChart" style="width: 50%; height: 400px;"></div>
        <div class="chart-item" ref="trendChart" style="width: 50%; height: 400px;"></div>
      </div>

    </div>

    <div class="dashboard-summary">
      <div class="summary-card">
        <h3>房源总数</h3>
        <p class="highlight">1,234套</p>
        <p class="trend up">较上月增长5%</p>
      </div>
      <div class="summary-card">
        <h3>平均租金</h3>
        <p class="highlight">3,568元/月</p>
        <p class="trend down">较上月下降2%</p>
      </div>
      <div class="summary-card">
        <h3>热门区域</h3>
        <p class="highlight">二七区</p>
        <p class="trend">占比35%</p>
      </div>
      <div class="summary-card">
        <h3>主力房型</h3>
        <p class="highlight">一居室</p>
        <p class="trend">占比45%</p>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {findRoomPriceCount, findRoomTypeAndCount} from "@/api/Echarts/getroomtype";

export default {
  name: 'Dashboard',
  data() {
    return {
      rentalData: {
        prices: [],
        areas: [
          { name: '金水区', value: 35 },
          { name: '二七区', value: 28 },
          { name: '惠济区', value: 20 },
          { name: '管城区', value: 15 },
          { name: '中原区', value: 18 },
          { name: '上街区', value: 16 },
          { name: '中牟县', value: 17 },
          { name: '巩义市', value: 8 },
          { name: '荥阳市', value: 20 },
          { name: '新密市', value: 26 },
          { name: '新郑市', value: 23 }
        ],
        types: [
          { name: '一居室', value: 45 },
          { name: '两居室', value: 35 },
          { name: '三居室', value: 15 },
          { name: '四居室+', value: 5 }
        ],
        trends: [
          { month: '1月', price: 3200 },
          { month: '2月', price: 3100 },
          { month: '3月', price: 3300 },
          { month: '4月', price: 3400 },
          { month: '5月', price: 3500 },
          { month: '6月', price: 3600 },
          { month: '7月', price: 3700 },
          { month: '8月', price: 3800 },
          { month: '9月', price: 3750 },
          { month: '10月', price: 3650 },
          { month: '11月', price: 3550 },
          { month: '12月', price: 3450 }
        ]
      },
      charts: {
        priceChart: null,
        areaChart: null,
        typeChart: null,
        trendChart: null
      }
    };
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
  },
  methods: {
    initCharts() {

      // 初始化租金分布图表
      this.charts.priceChart = echarts.init(this.$refs.priceChart);
      this.charts.priceChart.setOption({
        title: {
          text: '租金分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: []
        },
        series: [
          {
            name: '租金分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.rentalData.prices.map(item => ({
              value: item.count,
              name: item.range
            }))
          }
        ]
      });

      // 初始化地区分布图表
      this.charts.areaChart = echarts.init(this.$refs.areaChart);
      this.charts.areaChart.setOption({
        title: {
          text: '地区分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: this.rentalData.areas.map(item => item.name)
        },
        series: [
          {
            name: '房源数量',
            type: 'bar',
            data: this.rentalData.areas.map(item => item.value),
            itemStyle: {
              color: (params) => {
                const colorList = ['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae','#749f83','#c23531','#2f4554','#61a0a8','#d48265','#91c7ae','#749f83'];
                return colorList[params.dataIndex];
              }
            }
          }
        ]
      });

      // 初始化房屋类型图表
      this.charts.typeChart = echarts.init(this.$refs.typeChart);
      this.charts.typeChart.setOption({
        title: {
          text: '房屋类型',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '房屋类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },

          }
        ]
      });

      // 初始化价格趋势图表
      this.charts.trendChart = echarts.init(this.$refs.trendChart);
      this.charts.trendChart.setOption({
        title: {
          text: '租金价格趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['平均租金'],
          top: 'bottom'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.rentalData.trends.map(item => item.month)
        },
        yAxis: {
          type: 'value',
          name: '价格(元)'
        },
        series: [
          {
            name: '平均租金',
            type: 'line',
            data: this.rentalData.trends.map(item => item.price),
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#1890ff'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(24, 144, 255, 0.5)'
                },
                {
                  offset: 1,
                  color: 'rgba(24, 144, 255, 0.1)'
                }
              ])
            }
          }
        ]
      });
    },
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize();
        }
      });
    },

    // 查询房屋类型和数量
    fetchRentalTypes() {
      findRoomTypeAndCount().then(ret => {
        if (ret.code === 20000) {
          this.rentalData.types = ret.data
          // 动态更新 typeChart 图表
          this.updateDynamicTypeChart();
          this.updateDynamicPriceChart(); // 新增方法：用 types 更新 priceChart
        }
      }).catch(error => {
        console.log('请求查询全部报错: ', error);
      });
    },

    // 查询房屋价格和数量
    fetchRentalPriceCount() {
      findRoomPriceCount().then(res => {
        console.log('查询全部: ', res.data)
        if (res.code === 20000) {
          this.rentalData.prices = res.data
          // 动态更新 typeChart 图表
          this.updateDynamicPriceChart();
        }
      }).catch(error => {
        console.log('请求查询全部报错: ', error);
      });
    },

    // 动态更新 typeChart 图表
    updateDynamicTypeChart() {
      console.log('rentalData.types before update:', this.rentalData.types);
      if (this.charts.typeChart) {
        if (this.rentalData.types && this.rentalData.types.length > 0) {
          this.charts.typeChart.setOption({
            series: [{
              data: this.rentalData.types.map(item => ({
                value: item.roomNum,
                name: item.roomType
              }))
            }]
          });
        } else {
          // 数据为空时显示“暂无数据”
          this.charts.typeChart.showLoading('noData', {
            text: '暂无数据',
            fontSize: 20,
            textColor: '#666'
          });
        }
      }
    },

    // 动态更新 priceChart 图表
    updateDynamicPriceChart() {
      if (this.charts.priceChart) {
        if (this.rentalData.prices && this.rentalData.prices.length > 0) {
          this.charts.priceChart.setOption({
            legend: {
              data: this.rentalData.prices.map(item => item.priceRange)
            },
            series: [{
              data: this.rentalData.prices.map(item => ({
                value: item.priceCount,
                name: item.priceRange
              }))
            }]
          });
        } else {
          // 数据为空时显示“暂无数据”
          this.charts.priceChart.showLoading('noData', {
            text: '暂无数据',
            fontSize: 20,
            textColor: '#666'
          });
        }
      }
    },
  },
  created() {
    this.fetchRentalTypes();
    this.fetchRentalPriceCount();

  }
};
</script>

<style scoped>
.rental-dashboard {
  padding: 20px;
  font-family: 'Arial', sans-serif;
  color: #333;
  background-color: #f5f7fa;
}

.dashboard-title {
  text-align: center;
  color: #1890ff;
  margin-bottom: 5px;
}

.dashboard-subtitle {
  text-align: center;
  color: #666;
  margin-bottom: 30px;
  font-size: 16px;
}

.chart-container {
  margin: 20px 0;
}

.chart-row {
  display: flex;
  margin-bottom: 20px;
}

.chart-item {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 0 10px;
  padding: 10px;
}

.dashboard-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.summary-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  width: 23%;
  text-align: center;
}

.summary-card h3 {
  margin-top: 0;
  color: #666;
}

.highlight {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin: 10px 0;
}

.trend {
  font-size: 14px;
  color: #666;
}

.trend.up {
  color: #52c41a;
}

.trend.down {
  color: #f5222d;
}

@media (max-width: 768px) {
  .chart-row {
    flex-direction: column;
  }

  .chart-item {
    width: 100% !important;
    margin: 10px 0;
  }

  .dashboard-summary {
    flex-wrap: wrap;
  }

  .summary-card {
    width: 48%;
    margin-bottom: 15px;
  }
}
</style>
